package com.shenda.device.analysis;

import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.DecimalFormat;

import com.shenda.device.enums.Cjms;
import com.shenda.device.message.RespMsg_UploadStart;
import com.swak.utils.IOUtils;
import com.swak.utils.Ints;

/**
 * 采集模式 01 -- 采样陀螺仪
 * 
 * @author lifeng
 */
public class Cjms_01_Analysis extends DataFileAnalysis {

	OutputStreamWriter csv_out;
	OutputStreamWriter init_out; // 初始数据，按照步长设置数据，优化初始的读取速度
	int cjpv = 0; // 按照采集频率跳过
	int skip = 0; // 需跳过数
	int line = 0; // 记录行数
	int sn = 0; // 文件编号

	public Cjms_01_Analysis(String file) {
		this(new File(file));
	}

	public Cjms_01_Analysis(File file) {
		super(file);
	}

	@Override
	protected void doAnalysisHead(RespMsg_UploadStart head) throws IOException {
		this.csv_out = new OutputStreamWriter(this.open(this.getPartFileName(sn)));
		this.csv_out.write("Acc_x" + "," + "Acc_y" + "," + "Acc_z" + "\r\n");
		this.init_out = new OutputStreamWriter(this.open(new File(this.analysisFile, this.datFileName + ".skip.csv")));
		this.init_out.write("Acc_x" + "," + "Acc_y" + "," + "Acc_z" + "\r\n");
		this.cjpv = Ints.decodeHex(head.getOdr());
	}

	@Override
	protected void doAnalysisRecord(byte[] data) throws IOException {
		// 两字节数据
		byte[] temp = new byte[2];

		// 陀螺仪 数据
		temp[0] = data[1];
		temp[1] = data[0];
		int x1 = this.toUInt16(temp);
		temp[0] = data[3];
		temp[1] = data[2];
		int y1 = this.toUInt16(temp);
		temp[0] = data[5];
		temp[1] = data[4];
		int z1 = this.toUInt16(temp);

		// 陀螺仪
		Float gyr_x = Formater.Rad(x1);
		Float gyr_y = Formater.Rad(y1);
		Float gyr_z = Formater.Rad(z1);

		// 写入数据
		DecimalFormat decimalFormat = this.getDecimalFormat();
		String cvs = new StringBuilder().append(decimalFormat.format(gyr_x)).append(",")
				.append(decimalFormat.format(gyr_y)).append(",").append(decimalFormat.format(gyr_z)).append("\r\n")
				.toString();
		csv_out.append(cvs);

		// 序号
		line++;

		// 记录skip数据
		if (--skip <= 0) {
			init_out.append(cvs);
			skip = cjpv;
		}
		
		// 文件序号
		int sn = line / 100000;
		if (this.sn != sn) {
			this.sn = sn;
			IOUtils.closeQuietly(this.csv_out);
			this.csv_out = new OutputStreamWriter(this.open(this.getPartFileName(sn)));
		}
	}

	@Override
	protected int getRecordLength() {
		return Cjms.Acc.getRecord();
	}

	@Override
	public void close() throws IOException {
		IOUtils.closeQuietly(csv_out);
		IOUtils.closeQuietly(init_out);
	}
}
